import os
import logging
import traceback
import tornado.web
from tornado.escape import json_decode
from typing import Union
from utils.handler_util import HandlerUtil
from utils.token_util import Token


class BaseHandler(tornado.web.RequestHandler):
    """
    自定义tornadoHandler，实现了数据库session的绑定
    """

    def write_error(self, status_code: int, **kwargs) -> None:
        for line in traceback.format_exception(*kwargs["exc_info"]):
            logging.exception(line)
        self.write(HandlerUtil.set_failure_response(data={}, message="内部错误", status=100))
        self.finish()

    def write_file(self, filename, outfilname):
        self.set_header('Content-Type', 'application/octet-stream')
        self.set_header('Content-Disposition', 'attachment; filename={}'.format(outfilname))
        with open(filename, "rb") as f:
            while True:
                data = f.read(4096)
                if not data:
                    break
                self.write(data)
        self.finish()
        os.remove(filename)

    def set_default_headers(self):
        '''解决强求getjson跨越的问题'''
        # origin_url = self.request.headers.get('Origin')
        # self.set_header("Access-Control-Allow-Origin", 'http://10.1.6.51:8081')
        self.set_header("Access-Control-Allow-Origin", 'http://192.168.31.46:8081')
        # self.set_header("Access-Control-Allow-Origin", 'http://192.168.1.10:8081')
        self.set_header("Access-Control-Allow-Credentials", "true")
        # self.set_header("Access-Control-Allow-Headers", "x-requested-with,application/x-www-forms-urlencoded")
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PATCH, DELETE, PUT')
        self.set_header('Access-Control-Allow-Headers',
                        'Origin, X-Requested-With, Content-Type, Accept,Access-Control-Allow-Headers,'
                        'Access-Control-Allow-Origin')

    @staticmethod
    def parse_form_data(data):
        json_data = {}
        for item in data.split("&"):
            _item = item.split("=")
            _k, _v = _item[0], _item[1]
            json_data[_k] = _v
        return json_data

    def get_current_username(self):
        head = self.request.headers
        authorization = head.get("Authorization", None)
        decode_info = Token().decode_jwt(authorization)
        return decode_info.get("username", None)

    def get_current_userinfo(self):
        head = self.request.headers
        authorization = head.get("Authorization", None)
        decode_info = Token().decode_jwt(authorization)
        return decode_info

    def write(self, chunk: Union[str, bytes, dict], uid=-1, *args, **kwargs):
        return super(BaseHandler, self).write(chunk, *args, **kwargs)

    def prepare(self, *args, **kwargs):
        self.db_session = self.application.db_session

        # 获取到请求体的原始数据
        body = self.request.body
        # 判断格式是否为json，如果是json，进行json解码
        content_type = self.request.headers.get('Content-Type')
        self.request_data = {}
        if str(content_type).startswith("application/json"):
            if body:
                self.request_data = json_decode(body)

    def on_finish(self):
        self.db_session.remove()
